<!-- 分类维护 -->
<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level <= 2" type="text" size="mini" @click="append(data)">添加</el-button>
          <el-button type="text" size="mini" @click="edit(data)">修改</el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="remove(node, data)"
          >删除</el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="菜单名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [], // 拖拽后更新的数据
      maxLevel: 0, // 拖动的最大层级
      menus: [],
      dialogVisible: false, // 打开对话框
      category: {
        name: "",
        parentCid: 0,
        catLevel: 1,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
        catId: null
      }, // 提交对象
      expandedKey: [], // 扩展的树
      defaultProps: {
        children: "child",
        label: "name"
      },
      title: "",
      confirmType: ""
    };
  },
  methods: {
    // 获得菜单
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get"
      }).then(({ data }) => {
        console.log("菜单数据查询成功", data.data);
        this.menus = data.data;
      });
    },
    // 批量保存
    batchSave() {
      // 3.更新到数据库
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({ data }) => {
        this.$message({
          message: "菜单排序等修改成功",
          type: "success"
        });
        this.getMenus();
        // 清空值
        this.updateNodes = []; // 拖拽后更新的数据
        this.maxLevel = 0; // 拖动的最大层级
        // 设置默认展开expandedKeys的节点
        this.expandedKey = this.pCid;
      });
    },
    // 批量删除
    batchDelete(){
      let catIds = [];
      let catName = [];
      let checkNodes = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中的叶子：", checkNodes)

      checkNodes.forEach(element => {
        catIds.push(element.catId)
        catName.push(element.name)
      });
      
      this.$confirm(`删除【${catName}】菜单, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false)
          }).then(({ data }) => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    allowDrop(drappingNode, dropNode, type) {
      // 1.被拖动的当前节点以及所在的父节点层数不能大于3

      console.log("allowDrop", drappingNode, dropNode, type);
      this.countNodeLevel(drappingNode);
      // 当前正在拖动的节点+父节点所在的深度不大于3即可

      let deep = Math.abs(this.maxLevel - drappingNode.level) + 1;
      console.log("深度", deep);

      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
      return false;
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log("handleDrop:", draggingNode, dropNode, dropType);

      // 1.当前节点的最新的父节点的id
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);

      // 2.当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          // 如果遍历的是当前正在拖拽的节点
          let catLevel = draggingNode.level;
          if (siblings[i].level != draggingNode.level) {
            // 当前节点的层级发生变化
            catLevel = siblings[i].level;
            // 修改子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      console.log("updateNodes:", this.updateNodes);
    },
    // 递归修改子节点的层级
    updateChildNodeLevel(node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    countNodeLevel(node) {
      // 找到所有子节点，求出最大深度
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level;
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    // 对话框确定
    confirmSubmit() {
      if (this.confirmType == "add") {
        this.appendCategory();
      } else if (this.confirmType == "edit") {
        this.editCategory();
      }
    },
    // 添加菜单
    appendCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false)
      }).then(({ data }) => {
        this.$message({
          message: "添加成功",
          type: "success"
        });
        this.dialogVisible = false;
        this.getMenus();
        // 设置默认展开expandedKeys的节点
        this.expandedKey = [this.category.parentCid];
      });
    },
    // 修改菜单
    editCategory() {
      var { catId, name, icon, productUnit } = this.category;
      // var data = {
      //   catId: catId,
      //   name: name,
      //   icon: icon,
      //   productUnit: productUnit
      // }; ==> { catId, name, icon, productUnit }
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false)
      }).then(({ data }) => {
        this.$message({
          message: "修改成功",
          type: "success"
        });
        this.dialogVisible = false;
        this.getMenus();
        // 设置默认展开expandedKeys的节点
        this.expandedKey = [this.category.parentCid];
      });
    },
    // 打开添加对话框
    append(data) {
      this.dialogVisible = true;
      this.title = "添加分类";
      this.confirmType = "add";
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.productUnit = "";
      this.category.name = "";
      this.category.icon = "";
      this.category.catId = null;
      this.category.sort = 0;
      this.category.showStatus = 1;

      console.log("菜单", this.category);
      console.log("append", data);
    },
    // 打开修改对话框
    edit(data) {
      this.dialogVisible = true;
      this.title = "修改分类";
      this.confirmType = "edit";

      // 查询到最新的需要修改的菜单
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get"
      }).then(({ data }) => {
        console.log("查询到需要修改的菜单：", data.category);
        this.category.name = data.category.name;
        this.category.icon = data.category.icon;
        this.category.productUnit = data.category.productUnit;
        this.category.catId = data.category.catId;
        this.category.parentCid = data.category.parentCid;
      });
    },
    // 删除菜单
    remove(node, data) {
      // 删除某菜单
      this.$confirm(`删除【${data.name}】菜单, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.getMenus();
            // 设置默认展开expandedKeys的节点
            this.expandedKey = [node.parent.data.catId];
          });
        })
        .catch(() => {});
      console.log("append", node, data);
    }
  },
  //import引入的组件需要注入到对象中才能使用
  components: {},

  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},

  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getMenus();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
</style>